import requests
import time

import loginRequest
import testLogin


def processByCode(code):
    getOpenIdResponse = get_open_id_and_union_id(code)
    Cookie = 'JSESSIONID='+getOpenIdResponse['sessionId']
    print("获取openId成功",getOpenIdResponse)
    # print(Cookie)
    # loginRequest.loginAction(Cookie,getOpenIdResponse['encryptValue']
    #                          ,getOpenIdResponse['openId'],getOpenIdResponse['unionId'])
    testLogin.loginAction(Cookie, getOpenIdResponse['encryptValue']
                             , getOpenIdResponse['openId'], getOpenIdResponse['unionId'])
    print("执行登录")
def get_open_id_and_union_id(code):
    # 请求的 URL
    url = 'https://xcx.xybsyw.com/common/getOpenId.action'

    # 请求头
    headers = {
        'Host': 'xcx.xybsyw.com',
        'Connection': 'keep-alive',
        'content-type': 'application/x-www-form-urlencoded',
        'Accept-Encoding': 'gzip,compress,br,deflate',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.56(0x18003838) NetType/WIFI Language/zh_CN',
        'Referer': 'https://servicewechat.com/wx9f1c2e0bbc10673c/477/page-frame.html'
    }
    # 请求体数据
    data = {
        'code': code  # 使用传入的 code 参数
    }

    start_time = time.time()
    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, data=data)
        # 检查响应状态码
        response.raise_for_status()
        getOpenIdReponseDict = response.json()
        getOpenIdReponseData = getOpenIdReponseDict['data']
        # unionId = getOpenIdReponseData['unionId']
        # encryptValue = getOpenIdReponseData['encryptValue']
        # openId = getOpenIdReponseData['openId']
        # sessionId = getOpenIdReponseData['sessionId']
        # print(f'unionId: {unionId}')
        # print(f'encryptValue: {encryptValue}')
        # print(f'openId: {openId}')
        # print(f'sessionId: {sessionId}')
        end_time = time.time()
        # print(f"get_open_id_and_union_id took {end_time - start_time:.2f} seconds")
        return getOpenIdReponseData
    except requests.exceptions.HTTPError as http_err:
        print(f'HTTP 错误发生: {http_err}')
        return None
    except requests.exceptions.RequestException as req_err:
        print(f'请求发生错误: {req_err}')
        return None
